import { create } from "zustand";
import { immer } from "zustand/middleware/immer";
import { ModalIf, ModalListIf } from "../../core/types/modal";
import { createTimeStamp } from "../../util/crypto";

export type ModalState = {
    modals: ModalListIf;
};
export type ModalActions = {
    setModals: (modals: ModalListIf) => void;
    getModal: (modalId: string) => ModalIf | undefined;
    toggleModal: (modalId: string) => void;
    destroyModal: (modalId: string) => void;
    openModal: (modal: modalArg) => void;
    alert: (content: string, title?: string, onOk?: () => void) => void;
    error: (content: string, title?: string, onOk?: () => void) => void;
    confirm: (modal: modalArg) => void;
};
export type ModalStore = ModalState & ModalActions;
export type modalArg = {
    type?: "alert" | "confirm";
    variant?: string;
    title?: string;
    content: string;
    onOK?: () => void;
    onCancel?: () => void;
};

const modalStore = immer<ModalStore>((set, get) => ({
    modals: [],
    setModals: (modals: ModalListIf) => set({ modals }),
    getModal: (modalId: string) => {
        return get().modals.find((modal) => modal.id === modalId);
    },
    toggleModal: (modalId: string) => {
        set((state) => {
            const modal = state.modals.find((modal) => modal.id === modalId);
            if (!modal) {
                console.warn("modal not found", modalId);
                return;
            }
            modal.isOpen = !modal?.isOpen;
        });
    },
    destroyModal: (modalId: string) => {
        set((state) => {
            state.modals = state.modals.filter((modal) => modal.id !== modalId);
        });
    },
    openModal({ title, content, onOK, onCancel, type }: modalArg) {
        set((state) => {
            const modal: ModalIf = {
                id: createTimeStamp(),
                type: type || "alert",
                isOpen: true,
                title: title || "提示",
                content,
                onOk: onOK,
                onCancel: onCancel,
            };
            state.modals.push(modal);
        });
    },
    alert(content, title, onOK) {
        const state = get();
        state.openModal({ title, content, onOK, type: "alert" });
    },
    error(content, title, onOK) {
        const state = get();
        state.openModal({
            title,
            content,
            onOK,
            type: "alert",
            variant: "error",
        });
    },
    confirm({ title, content, onOK, onCancel }: modalArg) {
        const state = get();
        state.openModal({ title, content, onOK, onCancel, type: "confirm" });
    },
}));

export const useModal = create<ModalStore>()(modalStore);
